package Network

import (
	"encoding/json"
	"fmt"
	"logs"
	"net/http"
	"time"
)

type HTTPResult struct {
	Code    int
	Message string
	Result  interface{}
}

func printRequestInfo(req *http.Request) {
	//logs.PrintParent(fmt.Println(time.Now(), req.RemoteAddr, req.Method, req.URL.Path))
	logs.Print(time.Now(), req.RemoteAddr, req.Method, req.URL.Path)
}

func (r HTTPResult) String() string {
	return fmt.Sprintf("httpResult\nCode:%v\nMessage:%v\nResult:%v\n", r.Code, r.Message, r.Result)
}

func configHTTP(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")                    //允许访问所有域
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type,Origin") //header的类型
	w.Header().Add("Content-Type", "application/json;charset=utf-8")      //返回数据格式是json

	req.ParseForm()
	printRequestInfo(req)
}

func writeHTTPResult(w http.ResponseWriter, errCode int, errMsg string, obj interface{}) {
	//w.WriteHeader(http.StatusOK)
	res := HTTPResult{errCode, errMsg, obj}
	// JSON, err := json.Marshal(res)
	JSON, err := json.MarshalIndent(res, "", "\t")
	if err != nil {
		res = HTTPResult{errMarshalJSONFailed, "JSON解析失败！", nil}
		logs.Print(res)
		JSON, _ = json.Marshal(res)
		if JSON == nil {
			JSON = []byte("JSON解析失败！")
		}
		w.Write(JSON)
		return
	}
	w.Write(JSON)
}
